<template>
  <div class="register">
    <!-- <van-form ref="regForm" class="regForm" @submit.prevent="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="RegParams.tel"
          name="tel"
          label="手机号"
          placeholder="手机号"
          :rules="LoginRules.tel"
        />
        <van-field
          v-model="RegParams.password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="LoginRules.password"
        />
        <van-field
        v-model="CodeParams.telcode"
        center
        clearable
        label="短信验证码"
        placeholder="请输入短信验证码"
        :rules="LoginRules.telcode"
        :disabled="!isTelOk"
      >
        <template #button>
          <van-button size="small" type="primary" @click="sendCode">发送验证码</van-button>
        </template>
      </van-field>
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          注册
        </van-button>
      </div>
    </van-form> -->
  <!-- 选择手动提交 -->
  <van-form ref="regForm" class="regForm">
            <van-cell-group inset>
                <van-field v-model="RegParams.tel" name="tel" label="手机号" placeholder="手机号"
                    :rules="LoginRules.tel">
                </van-field>
                <van-field v-model="RegParams.password" :type="passwordShow ? 'text' : 'password'" name="password" label="密码"
                    placeholder="密码" :right-icon="passwordShow ? 'eye-o' : 'closed-eye'" @click-right-icon="onClickIcon"
                    :rules="LoginRules.password">
                </van-field>
                <van-field v-model="CodeParams.telcode" center clearable label="短信验证码"  placeholder="请输入短信验证码" :rules="LoginRules.telcode" :disabled="!isTelOk">
                    <template #button>
                        <van-button size="small" type="primary" @click="sendCode">发送验证码</van-button>
                    </template>
                </van-field>
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" @click="onSubmit">
                    提交
                </van-button>
            </div>
        </van-form>
  </div>
</template>


<script setup lang="ts">
// import { reactive,ref } from 'vue';
import {reactive,ref,toRef,getCurrentInstance} from 'vue'
import { reg } from '@/utils/rules';
import { doCheckPhoneAPI,doSendMsgCodeAPI,doCheckCodeAPI,doFinishRegisterAPI } from '../../api/user';
import { showSuccessToast,showFailToast } from 'vant';
import { result } from 'lodash';
import { useRoute,useRouter } from 'vue-router';
import router from '@/router';

/* const curr = getCurrentInstance();
const route = curr?.appContext.config.globalProperties.$route;
const router = curr?.appContext.config.globalProperties.$router;
console.log(1111,curr);

function useRoute(){
    const curr = getCurrentInstance();
    const route = curr?.appContext.config.globalProperties.$route;
    return route;
}

function useRouter(){
    const curr = getCurrentInstance();
    const router = curr?.appContext.config.globalProperties.$router;
    return router;
} */
const RegParams = reactive<RegParamsRaw>({
  tel:'15908621820',
  password:''
})
const CodeParams = reactive<CodeParams>({
  tel:toRef(RegParams,"tel"), //保持响应性 ref自动解包
  telcode:""
})
const passwordShow = ref(false);
const regForm =ref()
const isTelOk = ref(false);

let validateTel = function(value:any,rule:any):Promise<any>|boolean|string|void{
    console.log(rule,value);
      return new Promise(function(resolve,reject){
        doCheckPhoneAPI({tel:RegParams.tel}).then((result)=>{
          console.log(result);
          showSuccessToast("可以使用的手机号")
          resolve(true)
          isTelOk.value=true
        }).catch(()=>{
          reject(rule.message)//校验失败,返回失败的信息 
        })
      })
  }

  let validateCode = function(value:any,rule:any):Promise<any>|boolean|string|void{
    console.log(rule,value);
      return new Promise(function(resolve,reject){
        doCheckCodeAPI(CodeParams).then((result)=>{
          console.log(result);
          showSuccessToast("验证码校验成功")
          resolve(true)
        }).catch(()=>{
          resolve(rule.message)
        })
      })
  }

const LoginRules = reactive<RegRules>({
  tel: [
        { required: true, message: '请填写手机号', trigger: "onChange" },
        { pattern: reg.phone, message: '请填写正确的手机号', trigger: "onChange" },
        {validator:validateTel, message: '手机号已被注册', trigger: "onChange"}
    ],
    password: [
        { required: true, message: '请填写密码', trigger: "onChange" },
        { pattern: reg.pwd, message: '请输入6-16位的数字加字母', trigger: "onChange" },
    ],
    telcode: [
        { required: true, message: '请填写验证码', trigger: "onChange" },
        { validator:validateCode, message: '验证码输入错误', trigger: "onChange" }
    ],
})

const sendCode = ():void=> {
console.log(regForm.value);
regForm.value.validate("tel").then(()=>{
  console.log("校验成功");
  doSendMsgCodeAPI({tel:RegParams.tel}).then((result)=>{
    showSuccessToast("验证码发送成功")
    console.log("验证码发送成功",result);
    CodeParams.telcode = result.data // 假装收到验证码,输入到输入框
  }).catch(()=>{

  })
  
})
// .catch(()=>{
//   console.log(regForm.value);
  
// })


  // if(RegParams.tel){
  //   doSendMsgCodeAPI({tel:RegParams.tel})
  // }else{
  //   showFailToast("你小子！请先输入手机号")
  // }
}
const onClickIcon = () => {
    passwordShow.value = !passwordShow.value;
}
const onSubmit=()=>{
  console.log(regForm.value.getValidationStatus());
  let obj = regForm.value.getValidationStatus()

  let values = Object.values(obj)
  if(values.every((v)=>v==="passed")){
    console.log("可以注册");
    doFinishRegisterAPI(RegParams).then(()=>{
      router.push("./login")
    })
    
  }
}
</script>

<style lang="scss" scoped>
.register {
  background-color: #f7f8fa;

  .regForm {
    margin-top: 20px;
  }
}
</style>